this.name                        = "TigersTurf";
this.author                        = "Kaks,Arexack_Heretic,Murgh";
this.copyright                = "Creative Commons: attribution, non-commercial, sharealike.";
this.description        = "Gang warfare in the - what century is this? Includes all the ships in both Custom Paints & Custom Paints & Racers";
this.version                = "0.52b";

this.minOolite="1.70";
//this.badOolite=["1.70"];
this.Log=function(str){
        if (typeof log != 'undefined') log("script."+this.name, str);
        else LogWithClass("script."+this.name, str);
}

this.canRun = function(){
        if (!this.badOolite) this.badOolite=[];
        if (typeof oolite == 'undefined') {        //'oolite' undefined before v1.70,
                if(this.minOolite-0<1.7) return true;
                this.Log("--- Script disabled. Requires Oolite v"+this.minOolite);
                return false;
        }
        if (oolite.compareVersion(this.minOolite) > 0){
                this.Log("--- Script disabled. Requires Oolite v"+this.minOolite);
                return false;
        }
        for (var i=this.badOolite.length;i>0;i--){
                if (oolite.compareVersion(this.badOolite[i-1]) == 0){
                        this.Log("--- Script disabled to avoid bugs in Oolite v"+oolite.versionString+". Please use another version. ");
                        return false;
                }
        }
        return true;
}

this.gangUp= function(){
                let t,i,ships=system.shipsWithRole('tigers');
                for (i=ships.length;i>0;i--){
                        t=ships[i-1];
                        t.switchAI('tigerAI.plist');
                        t.reactToAIMessage('ATTACK_PLAYER');
                }
}

this.launchBoss= function(num,whereTo){
        if (whereTo==0){ //plain number, use addsystemships
                system.legacy_addSystemShips('tigerboss',num,0);//At least 2 ships - includes 1 escort, but will be 3 if the escort itself is a boss, and so on
                let n=this.anyInt(0,num*3); //including the 1 escort, we'll  have between 1 and 4 'soldiers' per boss.
                if (n>0)
                        system.legacy_addSystemShips('tigers',n,0);
                return n+num*2;
        }else{ // we assume we have an array & use addshipsat
                system.legacy_addShipsAt('tigerboss',num,'pwm',whereTo);
                let n=this.anyInt(0,num*3);
                if (n>0)
                        system.legacy_addShipsAt('tigers',num,'pwm',whereTo);
                return n+num*2;//more if bosses spawn bosses too!
        }
}

this.anyInt= function(n1,n2){
                return Math.round(Math.random()*(n2-n1)+n1);
}

this.abs2pwm=function(pos){
        //witchpoint finder, trust no-one version!
        //LogWithClass("script."+this.name,'abs coordinates '+ pos);
        let tmp=system.shipsWithRole('wbuoy-finder');
        for (let i=tmp.length;i>0;i--){
                tmp[i-1].becomeExplosion();
                delete tmp[i-1];
        }
        system.legacy_addShipsAtPrecisely('wbuoy-finder',1,'wpm',[0,0,-10]);
        tmp=system.shipsWithRole('wbuoy-finder')[0];
        //let w=system.shipsWithRole('buoy-witchpoint',tmp)[0];
        //LogWithClass("script."+this.name,"w "+w.position,'wf '+tmp.position.add(0,0,10));
        let w=tmp.position.add(0,0,10); //close enough!
        delete tmp;

        let p=system.mainPlanet.position;
        let z=p.subtract(w).direction();
        let x=p.subtract(system.sun.position).direction();
        let y=z.cross(x);
        x=z.cross(y);
        let v=pos.subtract(p);
        let d=v.direction();
        let l=v.magnitude();
        //LogWithClass("script."+this.name,'pwm coordinates  '+([d.dot(x)*l,d.dot(y)*l,-d.dot(z)*l]));
        return [d.dot(x)*l,d.dot(y)*l,-d.dot(z)*l];
}

this.startUp = this.reset = function(){
        if (!this.canRun()){
                delete this.shipExitedWitchspace;
                delete this.shipLaunchedFromStation;
        }
        if (!missionVariables.hotrods){
                missionVariables.hotrods=this.version; // save the script version
                missionVariables.hotrods_tigersturf=0;
        }
        if (missionVariables.hotrods!=this.version){
                this.Log("Savegame used Hotrods v"+missionVariables.hotrods+ ", updating to v"+this.version);
                //  do whatever is necessary
                missionVariables.hotrods=this.version;
        }
}

this.shipExitedWitchspace = function(){
        missionVariables.hotrods_tigersturf_sID=-1;
        // max nr of times we meet the gang: between 5 & 10 - if we meet bosses, it counts for 2 encounters.
        if ( missionVariables.hotrods_tigersturf> 9 || system.ID > 99 || player.score<30) return;
        let n,m=missionVariables.hotrods_tigersturf;
        let d100=Math.round(Math.random()*100);
        if (system.government==0) d100-=33; //likelihood increases from 66% to 99% if inside an anarchy system
        this.Log(" Tigers encounter roll: "+d100);

        if (d100>65) return;

        player.consoleMessage((m<2?'Easy tiger! K':'Try and k')+'eep a low profile in this system.');
        missionVariables.hotrods_tigersturf_sID=system.ID; //tiger system
        /*        the bosses don't really appear the first & last few meetings - at the beginning, they don't know you exist,
                towards the end they've run out of bosses... :)        */
        if (d100<20 || d100<40 && m>3 && m<8){
                n=this.launchBoss(this.anyInt(2,5),0);//they can spawn bosses too!
                missionVariables.hotrods_tigersturf+=2;
        } else {
                system.legacy_addSystemShips('tigers',n=this.anyInt(3,5),0);
                missionVariables.hotrods_tigersturf++;
        }
        this.Log("Met "+(n>5?'at least ':'')+n+" members of the Tiger Gang in " + system.name) ;
}

this.shipLaunchedFromStation = function(){
        if (missionVariables.hotrods_tigersturf_sID != system.ID) return; //not a tiger system, bye
        missionVariables.hotrods_tigersturf_sID=-1;        // only once per tiger system!
        let s='';
        let n=system.shipsWithRole('tigers').length>7 ? 0 : this.anyInt(-2,5);
        if (n!=0){
                let stn=system.shipsWithRole('station')[0].position;
                let diff=(player.ship.position.subtract(stn)).multiply(3.5);
                let whereTo=player.ship.position.add(diff);
                //abs2pwm for 1.70, new methods soon for 1.71+
                if(n<0)
                        n=this.launchBoss(2,this.abs2pwm(whereTo));
                else
                        system.legacy_addShipsAt('tigers',n,'pwm',this.abs2pwm(whereTo));
                s=n+" more member"+(n>1?'s':'')+" of the Tiger Gang ";
                player.consoleMessage(s+(n>1?'have':'has')+' showed up.'+(n>3?' Great!':''));
                s+='in ';
        }
        //LogWithClass("script."+this.name,system.shipsWithRole('tigers').length+' tigers altogheter. nearest tiger: ' +system.shipsWithRole('tigers')[0]);
		if(this.timer) {
			this.timer.stop();
			delete this.timer();
		}
        this.timer=new Timer(this, this.gangUp,2.5);
        if (n>0)
                this.Log(s+system.name +" spotted loitering with intent by one of the stations.") ;
}
this.playerWillEnterWitchspace = function() {
    if (this.timer) {
		this.timer.stop();
		delete this.timer;
	}
};
